package com.zwh.modbus.modbus4j;

import java.util.HashMap;
import java.util.Map;

import com.serotonin.modbus4j.ModbusMaster;

/**
 * @Author ody
 * @Description //TODO
 * @Date 2023/6/28 15:07
 **/
public class ModbusMasterCache {

    private static Map<String,ModbusMaster> modbusMasterMap = null;

    private static Map<String,Integer> countMap = null;

    public static synchronized Map<String,ModbusMaster> getModbusMasterMap(){
        if(modbusMasterMap == null){
            modbusMasterMap = new HashMap<>();
            countMap = new HashMap<>();
        }
        return modbusMasterMap;
    }

    public static void setModbusMaster(String key,ModbusMaster modbusMaster){
        getModbusMasterMap().put(key,modbusMaster);
        Integer count = countMap.get(key);
        if(count == null){
            count = 0;
        }
        countMap.put(key,++count);
    }

    public static void setCount(String key){
        Integer count = countMap.get(key);
        countMap.put(key,++count);
    }

    public static Map<String,Integer> getCountMap(){
        if(countMap == null){
            return null;
        }else {
            return countMap;
        }
    }

    public static ModbusMaster getModbusMaster(String key){
        ModbusMaster modbusMaster = getModbusMasterMap().get(key);
        if(modbusMaster == null){
            return null;
        }
        return modbusMaster;
    }

    public static boolean removeModbusMaster(String key){
        if(countMap == null){
            return false;
        }
        Integer count = countMap.get(key);
        if(count == 1){
            getModbusMasterMap().remove(key);
            countMap.put(key,0);
            return true;
        }else if(count > 1){
            countMap.put(key,--count);
            return false;
        }
        return true;
    }
}
